package com.github.iot.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.DialogFragment;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.github.iot.R;
import com.github.iot.adapter.ManageButtonAdapter;
import com.github.iot.adapter.ManageDoorAdapter;
import com.github.iot.adapter.ManageLightAdapter;
import com.github.iot.dao.CommonDaoUtils;
import com.github.iot.dao.DaoUtilsStore;
import com.github.iot.entity.Button;
import com.github.iot.entity.Door;
import com.github.iot.entity.Light;
import com.github.iot.entity.Showcase;
import com.github.iot.utils.ActivityUtils;
import com.github.iot.utils.BarUtils;
import com.github.iot.utils.FastJsonUtils;
import com.github.iot.utils.ToastUtils;
import com.github.iot.view.RxTitle;
import com.github.iot.view.dialogs.fragment.ListDialogFragment;
import com.github.iot.view.dialogs.fragment.SimpleDialogFragment;
import com.github.iot.view.dialogs.iface.IListDialogListener;
import com.github.iot.view.dialogs.iface.ISimpleDialogListener;
import com.yanzhenjie.recyclerview.OnItemMenuClickListener;
import com.yanzhenjie.recyclerview.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.SwipeMenuItem;
import com.yanzhenjie.recyclerview.SwipeRecyclerView;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 展柜Activity
 *
 * @Author: 梁声洪
 * @Date: 2019/12/28 00:34
 * @Version: v1.0.0
 */
public class ManageShowcaseActivity extends AppCompatActivity implements IListDialogListener, ISimpleDialogListener {

    @BindView(R.id.rx_title)
    RxTitle mTitle;

    @BindView(R.id.door_recycler_view1)
    SwipeRecyclerView mDoorRecyclerView;

    @BindView(R.id.light_recycler_view1)
    SwipeRecyclerView mLightRecyclerView;

    @BindView(R.id.button_recycler_view1)
    SwipeRecyclerView mButtonRecyclerView;

    private static Showcase showcase;
    private static List<Door> mDoors;
    private static List<Light> mLights;
    private static List<Button> mButtons;
    private static DialogFragment dialogFragment;
    private static final int REQUEST_LIGHT_DIALOG = 1;
    private static final int REQUEST_DOOR_DIALOG = 2;
    private static final int REQUEST_BUTTON_DIALOG = 3;
    private static final int REQUEST_LIST_SINGLE = 11;
    private static CommonDaoUtils<Door> doorDaoUtils = DaoUtilsStore.getInstance().getDoorDaoUtils();
    private static CommonDaoUtils<Light> lightDaoUtils = DaoUtilsStore.getInstance().getLightDaoUtils();
    private static CommonDaoUtils<Button> buttonDaoUtils = DaoUtilsStore.getInstance().getButtonDaoUtils();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        BarUtils.setStatusBarColor(this, R.color.colorPrimaryDark);
        setContentView(R.layout.activity_manage_showcase);

        ButterKnife.bind(this);
        String str = getIntent().getStringExtra("showcase");
        showcase = FastJsonUtils.strToBean(str, Showcase.class);

        initView();
        initData();
    }

    private void initView() {
        mTitle.setLeftFinish(this);
        mTitle.setTitle(showcase.getName());

        DividerItemDecoration divider = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
        divider.setDrawable(ContextCompat.getDrawable(this, R.drawable.divider));

        mDoorRecyclerView.addItemDecoration(divider);
        mDoorRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mDoorRecyclerView.setSwipeMenuCreator(doorSwipeMenuCreator);
        mDoorRecyclerView.setOnItemMenuClickListener(doorMenuItemClickListener);

        mLightRecyclerView.addItemDecoration(divider);
        mLightRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mLightRecyclerView.setSwipeMenuCreator(lightSwipeMenuCreator);
        mLightRecyclerView.setOnItemMenuClickListener(lightMenuItemClickListener);

        mButtonRecyclerView.addItemDecoration(divider);
        mButtonRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mButtonRecyclerView.setSwipeMenuCreator(lightSwipeMenuCreator);
        mButtonRecyclerView.setOnItemMenuClickListener(buttonMenuItemClickListener);
    }

    /**
     * 菜单创建器，在Item要创建菜单的时候调用。
     */
    private SwipeMenuCreator doorSwipeMenuCreator = (swipeLeftMenu, swipeRightMenu, position) -> {
        int width = getResources().getDimensionPixelSize(R.dimen.dp_70);

        int height = ViewGroup.LayoutParams.MATCH_PARENT;
        SwipeMenuItem deleteItem = new SwipeMenuItem(ManageShowcaseActivity.this).setBackground(R.drawable.selector_red)
                .setText("启用\nor\n隐藏")
                .setTextColor(Color.WHITE)
                .setWidth(width)
                .setHeight(height);
        swipeRightMenu.addMenuItem(deleteItem);

        SwipeMenuItem addItem = new SwipeMenuItem(ManageShowcaseActivity.this).setBackground(R.drawable.selector_green)
                .setText("修改")
                .setTextColor(Color.WHITE)
                .setWidth(width)
                .setHeight(height);
        swipeRightMenu.addMenuItem(addItem);
    };

    /**
     * 菜单创建器，在Item要创建菜单的时候调用。
     */
    private SwipeMenuCreator lightSwipeMenuCreator = (swipeLeftMenu, swipeRightMenu, position) -> {
        int width = getResources().getDimensionPixelSize(R.dimen.dp_70);

        int height = ViewGroup.LayoutParams.MATCH_PARENT;
        SwipeMenuItem deleteItem = new SwipeMenuItem(ManageShowcaseActivity.this).setBackground(R.drawable.selector_red)
                .setText("启用\nor\n隐藏")
                .setTextColor(Color.WHITE)
                .setWidth(width)
                .setHeight(height);
        swipeRightMenu.addMenuItem(deleteItem);

        SwipeMenuItem addItem = new SwipeMenuItem(ManageShowcaseActivity.this).setBackground(R.drawable.selector_green)
                .setText("修改")
                .setTextColor(Color.WHITE)
                .setWidth(width)
                .setHeight(height);
        swipeRightMenu.addMenuItem(addItem);
    };

    /**
     * RecyclerView的Item的Menu点击监听。
     */
    private OnItemMenuClickListener doorMenuItemClickListener = (menuBridge, position) -> {
        menuBridge.closeMenu();

        int direction = menuBridge.getDirection();
        int menuPosition = menuBridge.getPosition();

        if (direction == SwipeRecyclerView.RIGHT_DIRECTION) {
            Door door = mDoors.get(position);
            if (menuPosition == 0) {
                // 隐藏 or 修改
                String message = door.getStatus() == -1 ? "您确定要启动" + door.getName() + "吗？" : "您确定要隐藏" + door.getName() + "吗？";
                dialogFragment = SimpleDialogFragment.createBuilder(ManageShowcaseActivity.this, getSupportFragmentManager())
                        .setTitle("系统提示")
                        .setMessage(message)
                        .setPositiveButtonText("确定")
                        .setNegativeButtonText("取消")
                        .setCancelable(false)
                        .setTag(FastJsonUtils.obj2JsonStr(door))
                        .setRequestCode(REQUEST_DOOR_DIALOG)
                        .show();
            } else if (menuPosition == 1) {
                // 修改
                Bundle bundle = new Bundle();
                bundle.putInt("TAG", 2);
                bundle.putLong("showcaseId", showcase.getId());
                bundle.putString("door", FastJsonUtils.obj2JsonStr(door));
                ActivityUtils.skipActivity(ManageShowcaseActivity.this, DoorUpdateActivity.class, bundle);
            }
        }
    };

    private OnItemMenuClickListener lightMenuItemClickListener = (menuBridge, position) -> {
        menuBridge.closeMenu();

        int direction = menuBridge.getDirection();
        int menuPosition = menuBridge.getPosition();

        if (direction == SwipeRecyclerView.RIGHT_DIRECTION) {
            Light light = mLights.get(position);
            if (menuPosition == 0) {
                // 隐藏 or 修改
                String message = light.getStatus() == -1 ? "您确定要启动" + light.getName() + "吗？" : "您确定要隐藏" + light.getName() + "吗？";
                dialogFragment = SimpleDialogFragment.createBuilder(ManageShowcaseActivity.this, getSupportFragmentManager())
                        .setTitle("系统提示")
                        .setMessage(message)
                        .setPositiveButtonText("确定")
                        .setNegativeButtonText("取消")
                        .setCancelable(false)
                        .setTag(FastJsonUtils.obj2JsonStr(light))
                        .setRequestCode(REQUEST_LIGHT_DIALOG)
                        .show();
            } else if (menuPosition == 1) {
                // 修改
                Bundle bundle = new Bundle();
                bundle.putInt("TAG", 2);
                bundle.putLong("showcaseId", showcase.getId());
                bundle.putString("light", FastJsonUtils.obj2JsonStr(light));
                ActivityUtils.skipActivity(ManageShowcaseActivity.this, LightActivity.class, bundle);
            }
        }
    };

    private OnItemMenuClickListener buttonMenuItemClickListener = (menuBridge, position) -> {
        menuBridge.closeMenu();

        int direction = menuBridge.getDirection();
        int menuPosition = menuBridge.getPosition();

        if (direction == SwipeRecyclerView.RIGHT_DIRECTION) {
            Button button = mButtons.get(position);
            if (menuPosition == 0) {
                // 隐藏 or 修改
                String message = button.getStatus() == -1 ? "您确定要启动" + button.getName() + "吗？" : "您确定要隐藏" + button.getName() + "吗？";
                dialogFragment = SimpleDialogFragment.createBuilder(ManageShowcaseActivity.this, getSupportFragmentManager())
                        .setTitle("系统提示")
                        .setMessage(message)
                        .setPositiveButtonText("确定")
                        .setNegativeButtonText("取消")
                        .setCancelable(false)
                        .setTag(FastJsonUtils.obj2JsonStr(button))
                        .setRequestCode(REQUEST_BUTTON_DIALOG)
                        .show();
            } else if (menuPosition == 1) {
                // 修改
                Bundle bundle = new Bundle();
                bundle.putString("button", FastJsonUtils.obj2JsonStr(button));
                ActivityUtils.skipActivity(ManageShowcaseActivity.this, ButtonActivity.class, bundle);
            }
        }
    };

    private void initData() {
        String sql = "WHERE SHOWCASE_ID = ? ORDER BY STATUS DESC, SORT ASC";
        String sql1 = "WHERE SHOWCASE_ID = ? ORDER BY STATUS DESC, TYPE ASC";
        mDoors = doorDaoUtils.queryByNativeSql(sql1, new String[]{String.valueOf(showcase.getId())});
        mLights = lightDaoUtils.queryByNativeSql(sql, new String[]{String.valueOf(showcase.getId())});
        mButtons = buttonDaoUtils.queryByNativeSql(sql, new String[]{String.valueOf(showcase.getId())});

        ManageDoorAdapter doorAdapter = new ManageDoorAdapter(ManageShowcaseActivity.this, mDoors);
        mDoorRecyclerView.setAdapter(doorAdapter);

        ManageLightAdapter lightAdapter = new ManageLightAdapter(ManageShowcaseActivity.this, mLights);
        mLightRecyclerView.setAdapter(lightAdapter);

        ManageButtonAdapter buttonAdapter = new ManageButtonAdapter(ManageShowcaseActivity.this, mButtons);
        mButtonRecyclerView.setAdapter(buttonAdapter);
    }

    @Override
    public void onNegativeButtonClicked(int requestCode) {

    }

    @Override
    public void onNeutralButtonClicked(int requestCode) {

    }

    @Override
    public void onPositiveButtonClicked(int requestCode) {
        if (requestCode == REQUEST_LIGHT_DIALOG) {
            String tag = dialogFragment.getTag();
            if (null != tag) {
                Light light = FastJsonUtils.strToBean(tag, Light.class);
                Integer status = light.getStatus() == -1 ? 1 : -1;
                light.setStatus(status);
                boolean flag = lightDaoUtils.update(light);
                if (flag) {
                    ToastUtils.success("操作成功");
                    initData();
                } else {
                    ToastUtils.error("操作失败");
                }
            }
        }

        if (requestCode == REQUEST_DOOR_DIALOG) {
            String tag = dialogFragment.getTag();
            if (null != tag) {
                Door door = FastJsonUtils.strToBean(tag, Door.class);
                Integer status = door.getStatus() == -1 ? 1 : -1;
                door.setStatus(status);
                boolean flag = doorDaoUtils.update(door);
                if (flag) {
                    ToastUtils.success("操作成功");
                    initData();
                } else {
                    ToastUtils.error("操作失败");
                }
            }
        }

        if (requestCode == REQUEST_BUTTON_DIALOG) {
            String tag = dialogFragment.getTag();
            if (null != tag) {
                Button button = FastJsonUtils.strToBean(tag, Button.class);
                Integer status = button.getStatus() == -1 ? 1 : -1;
                button.setStatus(status);
                boolean flag = buttonDaoUtils.update(button);
                if (flag) {
                    ToastUtils.success("操作成功");
                    initData();
                } else {
                    ToastUtils.error("操作失败");
                }
            }
        }
    }

    @Override
    public void onListItemSelected(CharSequence value, int number, int requestCode) {
        Log.i("LSHENGH", "onListItemSelected: " + value);
        Log.i("LSHENGH", "onListItemSelected: " + number);
        Log.i("LSHENGH", "onListItemSelected: " + requestCode);
        if (requestCode == REQUEST_LIST_SINGLE) {
            Bundle bundle = new Bundle();
            bundle.putInt("TAG", 1);
            bundle.putString("doorType", value.toString());
            bundle.putLong("showcaseId", showcase.getId());
            ActivityUtils.skipActivity(ManageShowcaseActivity.this, DoorActivity.class, bundle);
        }
    }

    @OnClick({R.id.fab})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.fab:
                ListDialogFragment
                        .createBuilder(ManageShowcaseActivity.this, getSupportFragmentManager())
                        .setTitle("请选择您要添加的信息")
                        .setItems(new String[]{"柜门", "背板", "灯箱"})
                        .setRequestCode(REQUEST_LIST_SINGLE)
                        .setChoiceMode(AbsListView.CHOICE_MODE_SINGLE)
                        .setCancelable(false)
                        .show();
                break;
            default:

                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        initData();
    }

}
